package main.java.FSMDE.models;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import main.java.ERMDE.models.Attribute;
import main.java.ERMDE.models.Entity;


public class RelatedComponent extends ComplexComponent {

	private Map<Component, ErmFsmRelationSet> relations;

	protected RelatedComponent(UUID componentId, String componentName,
			ComponentType componentType) {
		super(componentId, componentName, componentType);
		relations = new HashMap<Component, ErmFsmRelationSet>();
	}

	protected RelatedComponent(UUID componentId, String componentName,
			ComponentType componentType,
			ComponentCollection componentsCollection) {
		super(componentId, componentName, componentType, componentsCollection);
	}

	public Component setRelationToErmAttribute(main.java.ERMDE.models.Diagram diagram,
			Entity entity, Attribute attribute) throws Exception {

		if (diagram.getEntities().get(entity.getName()) == null) {
			throw new Exception("Diagram/Entity not related");
		}
		if (entity.getAttributes().getAttribute(attribute.getName()) == null) {
			throw new Exception("Entity/attribute not related");
		}

		ErmFsmRelationSet relationSet = new ErmFsmRelationSet(diagram, entity,
				attribute);
		Component textField = FactoryComponent.create(relationSet
				.getAttribute().getName(), ComponentType.Text_field);
		getComponents().add(textField);
		relations.put(textField, relationSet);
		textField.showRelationWithErmDiagram(relationSet);
		return textField;
	}

	public void removeRelationWithErmModel(Component textFieldComponent) {
		getComponents().remove(textFieldComponent);
		relations.remove(textFieldComponent);
	}

	public void setRelationToErmEntity(main.java.ERMDE.models.Diagram diagram,
			Entity entity) throws Exception {

		for (Attribute attribute : entity.getAttributes()) {
			setRelationToErmAttribute(diagram, entity, attribute);
		}
	}

	public List<Component> getRelatedComponents() {
		List<Component> components = new ArrayList<Component>();
		for (Component iteratedComponent : getComponents()) {
			if (relations.containsKey(iteratedComponent)) {
				components.add(iteratedComponent);
			}
		}
		return components;
	}

	public ErmFsmRelationSet getRelatedErmModel(Component component) {
		return relations.get(component);
	}
}
